package com.suqiu.qqrobot.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.suqiu.qqrobot.common.result.Result;
import com.suqiu.qqrobot.common.result.ResultCodeEnum;
import com.suqiu.qqrobot.utils.JwtUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器类
 */
@Component
public class RequestInterceptor implements HandlerInterceptor {

    private final static String PRE_TOKEN = "Bearer ";
    private final static String AUTHORIZATION_HEADER = "Authorization";
    private final static String CONTENT_TYPE = "application/json";

    /**
     * 访问控制器方法前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String token = request.getHeader(AUTHORIZATION_HEADER).replace(PRE_TOKEN, "");
        if (!JwtUtil.verify(token)) {
            response.setContentType(CONTENT_TYPE);
            response.setStatus(Integer.parseInt(ResultCodeEnum.UNAUTHORIZED.getCode()));
            response.getWriter().write(JSONObject.toJSONString(Result.fail(ResultCodeEnum.UNAUTHORIZED)));
            return false;
        }
        return true;
    }
}
